import axios from 'axios'
import {
  Notification,
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken,
  getCsrfToken
} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import Utils from '@/libs/framework/util'
import Constant from '@/libs/framework/constant'
import qs from 'qs'
import Vue from 'vue'

// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 150000
})
// request拦截器
service.interceptors.request.use(config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  let token = getToken()
  if (token && !isToken) {
    config.headers['championsoftTokenAuthorization'] = 'championsoft ' + token // 让每个请求携带自定义token 请根据实际情况自行修改
  }

  let csrfToken = getCsrfToken()
  if (csrfToken && !isToken) {
    config.headers[Constant.token.csrfToken] = csrfToken // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?';
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName];
      var part = encodeURIComponent(propName) + "=";
      if (value !== null && typeof (value) !== "undefined") {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            url += subPart + encodeURIComponent(value[key]) + "&";
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  if (!config.headers['Content-Type']) {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  }

  // Create POST Data
  let postData = null;
  const method = config.method.toUpperCase();

  if ((method === 'POST' || method === 'PUT' || method === 'PATCH') && config.data) {
    const postDataInstances = [ArrayBuffer, Blob, Document, FormData];
    // Post Data
    if (postDataInstances.indexOf(config.data.constructor) >= 0) {
      postData = config.data;
    } else {
      // POST Headers
      const boundary = `---------------------------${Date.now().toString(16)}`;
      let contentType = config.headers['Content-Type'];
      if (contentType === 'multipart/form-data') {
        config.headers['Content-Type'] = `multipart/form-data; boundary=${boundary}`;
      } else {
        // config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
      }
      postData = '';
      // qs 会把值为undefined的属性去掉
      let data = qs.stringify(config.data);
      if (contentType === 'multipart/form-data') {
        data = data.split('&');
        const newData = [];
        for (let i = 0; i < data.length; i += 1) {
          newData.push(`Content-Disposition: form-data; name="${data[i].split('=')[0]}"\r\n\r\n${data[i].split('=')[1]}\r\n`);
        }
        postData = `--${boundary}\r\n${newData.join(`--${boundary}\r\n`)}--${boundary}--\r\n`;
      } else if (contentType === 'application/json') {
        postData = JSON.stringify(config.data);
      } else {
        postData = data;
      }
    }
  }

  config.data = postData;

  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})
let toLogining = false;
// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    if (Utils.isString(code) && code != 'default') {
      return res.data
    }
    // 获取错误信息
    const fw = Vue.prototype.$framework;
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    if (code === 401 || code === 302) {
      if (!toLogining) {
        toLogining = true;
        MessageBox.confirm('由于您长时间未操作，登录已失效，请重新登录！', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('LogOut').then(() => {
            toLogining = false;
            fw.redirect.login();
          }).catch(() => {
            toLogining = false;
          });
        }).catch(() => {
          toLogining = false;
        });
      }
    } else if (code === 502) {
      fw.redirect.to("/502");
    } else if (code === 500) {
      Message({
        message: msg,
        type: 'error'
      })
      return Promise.reject(new Error(msg))
    } else if (code !== 200) {
      Notification.error({
        title: msg
      })
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  error => {
    let {
      message
    } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
